package com.itany.corejava.code13_jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author MissChen
 * @date 2024年03月22日 15:02
 */
public class Test09_事务 {
    public static void main(String[] args) throws DataAccessException {
        User user=new User("aaa","123456","12345698789","南京");
        insertUser(user);
    }
    public static void insertUser(User user) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {

            conn = JDBCUtil.getConnection();

            //开启事务
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_user ")
                    .append(" (username,password,phone,address) ")
                    .append(" values ")
                    .append(" (?,?,?,?) ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getPhone());
            ps.setString(4, user.getAddress());

            //执行DML操作
            int rows = ps.executeUpdate();
            // int i=10/0;
            //业务全部结束之后，提交事务，此时只要报错，则不会提交
            conn.commit();



        } catch (DataAccessException e) {
            System.out.println("---嘻嘻，你进入异常了---");
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new DataAccessException("事务回滚出错了");
            }
        } catch (SQLException e) {
            System.out.println("哈哈哈,您进入异常了");
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new DataAccessException("事务回滚出错了");
            }
        }catch (Exception e){
            System.out.println("---嘿嘿，你进入到异常了哇----");
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new DataAccessException("事务回滚出错了");
            }
        } finally {
            JDBCUtil.close(conn, ps, null);
        }
    }
}
